<template>
  <li :class="{ 'my-active-style': isActive(tabData) }">
    {{tabData.name}}
    &nbsp;
    <span v-if="allowClose()" class="my-btn-close" @click.stop="close()">&times;</span>
  </li>
</template>

<script lang="ts">
import { defineComponent, toRefs } from 'vue';
import { useRoute } from 'vue-router';

export default defineComponent({
  name: 'AmyTab',
  props: {
    tabData: Object
  },
  setup (props, context) {
    //当前路由对象
    const route = useRoute();

    //利用toRefs解构，不能用toRef
    const {
      tabData
    } = toRefs(props);

    //关闭Tab
    const close = () => {
      context.emit('tab-close', tabData.value);
    }

    //判断Tab是否是活动状态
    const isActive = () => {
      if (tabData.value) {
        return (route.path === tabData.value.path);
      }
      return false;
    }

    //当前路由非“主页”，允许关闭
    const allowClose = () => {
      if (tabData.value) {
        return tabData.value.path !== '/';
      }
      return false;
    }

    return {
      tabData,
      close,
      isActive,
      allowClose
    }
  }
})
</script>

<style lang="scss" scoped>
.my-active-style{
  background: $green-1;
}

>li {
  float: left;
  margin: 2px;
  padding: 5px 10px ;
  position: relative;
  color: #242323;

  &.loading:before {
    content: ' ';
    box-sizing: border-box;
    display: inline-block;
    width: 14px;
    height: 14px;
    position: absolute;
    left: 0px;
    top: 10px;
    border-radius: 9px;
    border: 2px solid #1ab394;
    border-top-color: transparent;
    border-left-color: transparent;
    animation: loading-rotate 0.8s infinite linear;
    -webkit-animation: loading-rotate 0.8s infinite linear;
  }

  &.active {
    color: #333;

    &:after {
      content: ' ';
      position: absolute;
      bottom: 0px;
      width: 100%;
      height: 2px;
      background-color: #1ab394;
      left: 0px;
    }

    .my-btn-close {
      opacity: 1;
    }
  }

  &:hover {
    cursor: pointer;
    background-color: $green-2;
    .my-btn-close {
      opacity: 1;
    }
  }

  .my-btn-close {
    position: absolute;
    display: inline-block;
    opacity: 0;
    top: 6px;
    right: 0px;
    line-height: 12px;
    width: 18px;
    height: 18px;
    border-radius: 14px;
    font-size: 18px;
    color: #999;
    transition: all 0.2s ease;

    &:hover {
      color: $orange-2;
      transform: scale(1.5);
      cursor: pointer;
    }
  }
}

</style>
